package com.shopping.service.impl;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Random;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import com.shopping.commons.response.DataGradResp;
import com.shopping.commons.response.MessageResp;
import com.shopping.commons.util.CommonCode;
import com.shopping.mapper.OrDetailsMapper;
import com.shopping.mapper.OrderMapper;
import com.shopping.model.Order;
import com.shopping.param.OrDetailsParam;
import com.shopping.param.OrderParam;
import com.shopping.response.OrderResp;
import com.shopping.service.IOrderService;

@Service
public class OrderService implements IOrderService{

	@Autowired
	private OrderMapper orderMapper;
	
	@Autowired 
	private OrDetailsMapper orDetailsMapper;
	
	private SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	
	public MessageResp insert(Order param) {
		MessageResp resp=new MessageResp();
		//TODO:   这里要对param进行一次加工，添加诸如  addrid    updateperson updatetime  delflag 
		//status     这样的一些参数
		Random r=new Random();
		param.setAddrid(r.nextInt(10000)+100000);//   100000-199999  之间的随机数
		param.setDelflag(CommonCode.DELFLAG_NORMAL);
		param.setCreatedate(sdf.format(new Date()));
		if(orderMapper.insertSelective(param)>0){
			//成功了
			resp.setCode("0000");
			resp.setMsg("添加成功");
		}else{
			resp.setCode("9999");
			resp.setMsg("添加失败");
		}
		return resp;
	}

	public MessageResp update(Order param) {
		MessageResp resp=new MessageResp();
		Order entity=orderMapper.selectByPrimaryKey(param.getOrderid());
		if(entity==null){
			//没找到
			resp.setCode("9999");
			resp.setMsg("未找到修改项");
			return resp;
		}
//		entity.setDelflag("1");
//		entity.setUpdatedate(sdf.format(new Date()));
		entity.setAddrid(param.getAddrid());
		entity.setDelflag(param.getDelflag()==null?CommonCode.DELFLAG_NORMAL:param.getDelflag());
		entity.setTotalnum(param.getTotalnum());
		//entity.setStatus(param.getStatus()==null?CommonCode.STATUS_ONE:param.getStatus());
		entity.setTotalprice(param.getTotalprice());
		entity.setUserid(param.getUserid());
		
		//自动更新   更新的时间  和更新的人
		entity.setUpdatedate(sdf.format(new Date()));
//		if(addressMapper.updateByPrimaryKey(param)>0){  hH会更新掉所有的字段，没有值的就用null覆盖
		if(orderMapper.updateByPrimaryKeySelective(entity)>0){
			//成功了
			resp.setCode("0000");
			resp.setMsg("修改成功");
		}else{
			resp.setCode("9999");
			resp.setMsg("修改失败");
		}
		return resp;
	}

	public MessageResp delete(Integer id) {
	//  在实现类中写的任何   与 接口无关的方法，都是在Controller中 不可见的
		MessageResp resp=new MessageResp();
			//TODO:如果没有这个id怎么办
			Order entity=orderMapper.selectByPrimaryKey(id);
			if(entity==null){
				//没找到
				resp.setCode("9999");
				resp.setMsg("未找到删除项");
				return resp;
			}
			entity.setDelflag(CommonCode.DELFLAG_DELETE);
			entity.setUpdatedate(sdf.format(new Date()));//asf.pares("2015-10-10 10:10:10")
//			try {
//				Integer.parseInt("1asdfa");
//			} catch (NumberFormatException e) {
//				e.printStackTrace();
//			}
			if(orderMapper.updateByPrimaryKeySelective(entity)>0){
				//成功了
				resp.setCode("0000");
				resp.setMsg("删除成功");
			}else{
				resp.setCode("9999");
				resp.setMsg("删除失败");
			}
			return resp;
	}

	public DataGradResp<Order> select(OrderParam param) {
		DataGradResp<Order> resp=new DataGradResp<Order>();
		//查询     可能有多个，可能是单个
		//如果前端没有传任何参数的话，delflag也要特殊处理下
		param.setDelflag(param.getDelflag()==null?"0":param.getDelflag());
		List<Order> orderList;
		try {
			orderList = orderMapper.select(param);
		} catch (Exception e) {
			e.printStackTrace();
			resp.setCode("9999");
			resp.setMsg("查询失败");
			return resp;
		}
		resp.setCode("0000");
		resp.setMsg("查询成功");
		resp.setRows(orderList);
		//resp.setObj(orderList);
		resp.setTotal(orderMapper.count(CommonCode.DELFLAG_NORMAL));
		return resp;
	}

	public DataGradResp<Order> select(Order param) {
		// TODO Auto-generated method stub
		return null;
	}

	public MessageResp batchDelete(String ids) {
		// TODO Auto-generated method stub
		return null;
	}

	public MessageResp addOrderAndDetails(OrderParam param) {
		MessageResp resp=new MessageResp();
		if(param.getAddrid()==0||param.getCommodityDetals()==null||param.getCommodityDetals().isEmpty()){
			resp.setCode(CommonCode.FAIL);
			resp.setMsg("参数错误");
			return resp;
		}
		Random r=new Random();
		Integer orderId=r.nextInt(10000)+100000;
		Integer orderDetailsId=0;
//		Object savePoint = TransactionAspectSupport.currentTransactionStatus().createSavepoint(); 
		//添加订单详情信息
		double totalPrice=0;
		int totalNum=0;
		for(HashMap item:param.getCommodityDetals()){
			orderDetailsId=r.nextInt(10000)+100000;
			OrDetailsParam detailsParam=new OrDetailsParam();
			detailsParam.setDetaid(orderDetailsId);
			detailsParam.setDelflag(CommonCode.DELFLAG_NORMAL);
			detailsParam.setOrderid(orderId);
			detailsParam.setCommid(Integer.parseInt(item.get("commid").toString()));
			detailsParam.setDetanum(Integer.parseInt(item.get("num").toString()));
			totalPrice+=Double.parseDouble(item.get("num").toString())*Double.parseDouble(item.get("price").toString());
//			totalPrice.add(new BigDecimal(item.get("num").toString()).multiply(new BigDecimal(item.get("price").toString())));
			totalNum+=Integer.parseInt(item.get("num").toString());
			detailsParam.setCreatedate(sdf.format(new Date()));
			if(orDetailsMapper.insertSelective(detailsParam)<0){
//				TransactionAspectSupport.currentTransactionStatus().rollbackToSavepoint(savePoint);
				resp.setCode(CommonCode.FAIL);
				resp.setMsg("下订失败");
				return resp;
			}
		}
		//添加订单信息   
		Order orderParam=new Order();
		orderParam.setDelflag(CommonCode.DELFLAG_NORMAL);
		orderParam.setStatus(CommonCode.ORDER_STATUS_ONE);
		orderParam.setOrderid(orderId);
		orderParam.setUserid(param.getUserid());
		orderParam.setAddrid(param.getAddrid());
		orderParam.setTotalnum(totalNum);
		orderParam.setTotalprice(new BigDecimal(totalPrice));
		orderParam.setCreatedate(sdf.format(new Date()));
		if(orderMapper.insertSelective(orderParam)<0){
//			TransactionAspectSupport.currentTransactionStatus().rollbackToSavepoint(savePoint);
			resp.setCode(CommonCode.FAIL);
			resp.setMsg("下订失败");
			return resp;
		}
		resp.setCode(CommonCode.SUCCESS);
		resp.setMsg("下订成功");
		return resp;
	}

	public List<OrderResp> findOrderAndDetails(Integer userid) {
		OrderParam param=new OrderParam();
		param.setUserid(userid);
		param.setDelflag(CommonCode.DELFLAG_NORMAL);
		return orderMapper.findOrderAndDetails(param);
	}

	
}
